import { createRef, RefObject } from 'react'
import type { Result } from 'ahooks/lib/useRequest/src/types'
import { produce } from 'immer'
import { create } from 'zustand'
import { AgGridReact } from '@ag-grid-community/react'

import { apiDelPublishRoute } from './apis'
import { IPublishRouteListItem, IPublishRouteListReq } from './interface'

export type TRequest = Result<IPublishRouteListItem[], [IPublishRouteListReq]>

export interface IStore {
  gridRef: RefObject<AgGridReact<IPublishRouteListItem>>
  request?: TRequest
  reqData: IPublishRouteListReq
  editingRowData: IPublishRouteListItem | null
  setReqData: (logisticsStatus: number, waybillNo?: string) => void
  setEditingRowData: (editingRowData: IPublishRouteListItem | null) => void
  getData: (scrollToTop?: boolean) => void
  delPublishRoute: (publishId: number) => Promise<void>
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    gridRef: createRef(),
    reqData: { logisticsStatus: -1, waybillNo: '' },
    editingRowData: null,
    setReqData: (logisticsStatus, waybillNo) => {
      set(prev => ({ reqData: { ...prev.reqData, logisticsStatus, waybillNo: waybillNo || prev.reqData.waybillNo } }))
    },
    setEditingRowData: editingRowData => set({ editingRowData }),
    getData: scrollToTop => {
      const { gridRef, request, reqData } = get()
      request?.run(reqData)
      if (scrollToTop) gridRef.current?.api?.ensureIndexVisible(0, 'top')
    },
    delPublishRoute: async publishId => {
      await apiDelPublishRoute(publishId)
      const mutate = get().request?.mutate
      mutate?.(oldData => {
        if (!oldData) return
        return produce(oldData, draft => {
          const target = draft.find(d => d.publishId === publishId)
          if (target) target.markFlag = 1
        })
      })
    },
  }
})
